<template>
	<view class="container goodsPay-container">
		<view class="pay-address" @click="jump('/pages/user/address?type=selectAddr')">
			<template v-if="addrInfo&&addrInfo.id">
				<view class="address-info">
					<view class="addr-top">{{addrInfo.selectSite}}</view>
					<view class="addr-mid">{{addrInfo.detailInfo}}</view>
					<view class="addr-bottom">{{addrInfo.consigneeName}} {{hidePhonePage(addrInfo.phone)}}</view>
				</view>
				<view class="addr-more iconfont">&#xe775;</view>
			</template>
			<view class="iconfont add-address" v-else>&#xe607; 选择地址</view>

		</view>


		<view class="goods-list" v-for="item in formData" :key="item.id">
			<view class="shop-name">{{item.placeMerchant}}</view>
			<view class="goods-info">
				<image class="goods-img" :src="item.picUrl" mode="aspectFill"></image>
				<view style="flex-grow: 1;">
					<view class="goods-name">{{item.goodsName}}</view>
					<view class="goods-pricebox">
						<text class="goods-price">¥{{$toYuan(item.addPrice)}}</text>
						<text class="goods-size">{{item.spuName}}</text>
					</view>
					<view style="font-size: 26rpx;color: #666;">数量：{{item.number}}</view>
					<!-- <view class="goods-numbox">
						<text class="iconfont" @click="clickMinus(item.id||'goods')">&#xe711;</text>
						<input class="goods-num" type="number" v-model="item.number" disabled>
						<text class="iconfont" @click="clickAdd(item.id||'goods')">&#xe607;</text>
					</view> -->
				</view>
			</view>
			<view class="order-mark">
				<text class="mark-title">订单备注:</text>
				<input class="mark-input" type="text" v-model="item.remark" placeholder="选填,请先和商家协商一致">
			</view>
		</view>
		<view class="coupon-box" @click="showCouponList=true">
			<text class="coupon-title">优惠券信息</text>
			<text class="coupon-info"
				v-if="couponInfo.name">{{couponInfo.name}},减{{$toYuan(couponInfo.discountAmount || 0)}}元</text>
			<text class="coupon-info" v-else>减0元</text>
			<text class="iconfont">&#xe775;</text>
		</view>

		<view class="page-bottom">
			<view style="color: #FF4F00;font-size: 24rpx;">¥</view>
			<view class="total-price">{{$toYuan(pageData.totalPrice-(couponInfo.discountAmount || 0))}}</view>
			<view class="count-info">
				<view>共{{pageData.countNum}}件</view>
				<view>抵扣：<text style="color: #FF4F00;">¥{{$toYuan(couponInfo.discountAmount || 0)}}</text></view>
			</view>
			<view style="flex-grow: 1;"></view>
			<view class="yuan-btn btn-success" @click="clickSure">提交订单</view>
		</view>

		<view class="coupon-list-box" :class="showCouponList&&'coupon-list-box-show'">
			<view class="coupon-list-main">
				<view class="iconfont coupon-box-close" @click="showCouponList=false">&#xe62c;</view>
				<view class="coupon-box-title">可用优惠券</view>
				<view class="coupon-list" v-for="item in couponList" :key="item.couponCode">
					<view style="width: 35%;text-align: center;">
						<text class="coupon-symbol">¥</text>
						<text class="coupon-number">{{$toYuan(item.discountAmount)}}</text>
					</view>
					<view class="dec-parent">
						<text class="coupon-dec dec-top"></text>
						<text class="coupon-dec dec-bottom"></text>
					</view>
					<view style="flex-grow: 1;">
						<view class="coupon-title">{{item.name}}</view>
						<view class="coupon-tips">满{{$toYuan(item.minAmount) }}可用</view>
					</view>
					<view class="yuan-btn coupon-btn " @click.stop="couponUse(item)">
						去使用
					</view>
				</view>
				<view style="text-align: center;color: #999;font-size: 26rpx;" v-if="couponList&&couponList.length===0">
					暂无可用</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onMounted, reactive, ref } from "vue";
	import { onShow, onLoad } from '@dcloudio/uni-app'
	import commonStore from '@/store/commonStore';
	import { doPay, getStorage, hideLoading, hidePhone, showLoading, showToast } from '@/common/util';
	import api from '@/common/api';
	let goodsList = []
	const formData = reactive<any>({})
	const pageData = ref({
		totalPrice: 0,
		countNum: 0
	})
	const showCouponList = ref(false)
	onShow(() => {
		getAddrInfo()
	})
	let goodsIds = []
	onMounted(async () => {
		const data = commonStore.state.payGoodsData
		goodsList = JSON.parse(JSON.stringify(data))
		goodsList.forEach(item => {
			goodsIds.push(item.goodsId)
			//购物车数据有购物车id  直接购买数据没有
			formData[item.id || 'goods'] = { ...item }
		})
		getPageData()
		getCouponInfo()

	})
	const couponInfo = ref<any>({})
	const couponList = ref([])
	const getCouponInfo = async () => {
		showLoading()
		try {
			const res = await api.findAvailableCoupons({
				"orderAmount": pageData.value.totalPrice,
				"goodsIds": goodsIds
			})
			const rows = res.data || []
			couponList.value = rows
			couponInfo.value = rows[0] || {}
			getPageData()
		} finally {
			hideLoading()
		}
	}
	const couponUse = (coupon) => {
		couponInfo.value = coupon
		showCouponList.value = false
		getPageData()
	}

	const getPageData = () => {
		let totalPrice = 0
		let countNum = 0
		for (let key in formData) {
			const item = formData[key]
			let number = Number(item.number)
			number = (isNaN(number) || number < 1) ? 1 : number
			totalPrice += item.addPrice * number
			countNum += number
		}
		pageData.value = { totalPrice, countNum }
	}
	const clickMinus = (id) => {
		if (formData[id].number === 1) return
		let number = Number(formData[id].number)
		number = isNaN(number) ? 1 : number
		formData[id].number = number - 1
		getPageData()
	}
	const clickAdd = (id) => {
		let number = Number(formData[id].number)
		number = isNaN(number) ? 1 : number
		formData[id].number = number + 1
		getPageData()
	}
	const addrInfo = ref<any>({})
	const getAddrInfo = () => {
		//如果store 有数据 取store数据，如果没有，去默认地址
		const storeAddr = commonStore.state.selAddr
		if (storeAddr && storeAddr.id) {
			addrInfo.value = storeAddr
		} else {
			getDefAddr()
		}
	}
	const getDefAddr = async () => {
		showLoading()
		try {
			const res = await api.getAddrList()
			const data = res.data
			addrInfo.value = data.find(item => {
				return item.isDefault === 1
			})
		} finally {
			hideLoading()
		}
	}
	const jump = (url) => {
		uni.navigateTo({
			url
		})
	}
	const hidePhonePage = (str) => {
		return hidePhone(str)
	}

	const clickSure = async () => {
		if (!addrInfo.value || !addrInfo.value.id) {
			showToast('请选择收货地址')
			return
		}
		let storeId = ''
		const goodsSpuDtoS = []

		// 获取分享人的id 只有从商品详情直接购买的商品才可能有分享id
		let shareUserId = ''
		for (let key in formData) {
			const item = formData[key]
			storeId = item.storeId
			shareUserId = item.shareUserId || ''
			goodsSpuDtoS.push({
				"id": item.goodsId,
				"specificationId": item.spuId,
				"quantity": item.number,
				"name": item.goodsName,
				"price": item.addPrice,
				"remark": item.remark,
				picture: item.picUrl,
				shoppingCartId: item.id || '' //购物车id
			})
		}
		const data = {
			goodsSpuDtoS,
			storeId,
			couponCode: couponInfo.value.couponCode || '',
			userCouponId: couponInfo.value.userCouponId || '',
			discountsGoodsSpuDtoS: couponInfo.value.goods,
			addressId: addrInfo.value.id,
			inviterUserId: shareUserId || '' // 绑定分享人的id
		}

		try {
			showLoading()
			const res = await api.placeAnOrder(data)
			commonStore.commit('addReload', 'carIndex')
			commonStore.commit('addReload', 'index')
			hideLoading()
			if (res.code === 200) {

				//下单成功，走支付流程

				doPay({ orderId: res.data.orderId, orderNo: res.data.orderNo }, () => {
					uni.redirectTo({
						url: "/pages/user/order"
					})
				}, () => {
					uni.redirectTo({
						url: "/pages/user/order"
					})
				})


			}
		} finally {
			//
		}
	}
</script>

<style lang="scss">
	.goodsPay-container {
		padding: 20rpx;
		padding-bottom: 130rpx;

		.pay-address {
			background-color: #fff;
			display: flex;
			align-items: center;
			padding: 20rpx;
			border-radius: 10rpx;
		}

		.add-address {
			width: 100%;
			text-align: center;
		}

		.address-info {
			flex-grow: 1;
		}

		.addr-top,
		.addr-bottom {
			font-size: 24rpx;
			color: #666;
		}

		.addr-mid {
			font-size: 34rpx;
			color: #333;
			margin: 10rpx 0;
		}

		.addr-more {
			color: #666;
			font-size: 25rpx;
		}

		.goods-list {
			background-color: #fff;
			border-radius: 10rpx;
			margin-top: 20rpx;
			padding: 20rpx;
		}

		.shop-name {
			font-size: 26rpx;
			color: #333;
			margin-bottom: 15rpx;
		}

		.goods-info {
			display: flex;
			align-items: center;
		}

		.goods-img {
			width: 200rpx;
			height: 200rpx;
			border-radius: 8rpx;
			margin-right: 20rpx;
			flex-shrink: 0;
		}

		.goods-name {
			font-size: 32rpx;
			color: #333;
		}

		.goods-pricebox {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.goods-price {
			font-size: 34rpx;
			color: #FF4F00;
			font-weight: bold;
			margin: 20rpx 0;
		}

		.goods-size {
			font-size: 24rpx;
			color: #666;
		}

		.goods-numbox {
			display: flex;
			align-items: center;

			.iconfont {
				font-size: 28rpx;
				color: #333;
				padding: 10rpx;
			}
		}

		.goods-num {
			width: 100rpx;
			border: solid 1px #eee;
			border-radius: 4rpx;
			padding: 5rpx 10rpx;
			text-align: center;
			margin: 0 10rpx;
			font-size: 28rpx;
		}


		.page-bottom {
			position: fixed;
			width: 100%;
			left: 0;
			bottom: 0;
			height: 120rpx;
			background-color: #fff;
			display: flex;
			align-items: center;
			padding: 0 20rpx;
			z-index: 99;

			.total-price {
				color: #FF4F00;
				font-size: 40rpx;
				font-weight: bold;
				margin-right: 25rpx;
				margin-left: 5rpx;
			}

			.count-info {
				font-size: 28rpx;
				color: #666;
			}

			.yuan-btn {
				height: 70rpx;
				width: 160rpx;
				border-radius: 8rpx;
				margin-left: 20rpx;
				font-size: 28rpx;
			}
		}



		.order-mark {
			display: flex;
			align-items: center;
			background-color: #fff;
			margin-top: 20rpx;
			padding: 20rpx;
			border-radius: 10rpx;

			.mark-title {
				font-size: 28rpx;
				color: #333;
			}

			.mark-input {
				font-size: 28rpx;
				flex-grow: 1;
				padding: 0 20rpx;
			}
		}

		.coupon-box {
			background-color: #fff;
			border-radius: 10rpx;
			margin-top: 20rpx;
			padding: 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.iconfont {
				font-size: 24rpx;
			}
		}


		.coupon-title {
			color: #333;
			flex-grow: 1;
			flex-shrink: 0;
			margin-right: 10rpx;
		}

		.coupon-info {
			color: #fff;
			background-color: #FF4F00;
			font-size: 28rpx;
			padding: 4rpx 20rpx;
			border-radius: 8rpx;
			margin-right: 10rpx;
		}

		.coupon-list-box {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.6);
			padding: 20rpx;
			z-index: 99;
			transform: scale3d(0, 0, 0);
		}

		.coupon-list-main {
			background-color: #fff;
			padding: 20rpx;
			max-height: 100%;
			overflow: auto;
			border-radius: 8rpx;
			position: relative;
			transform: translateX(200%);
			transition: all 0.3s;
		}

		.coupon-list-box-show {
			transform: scale3d(1, 1, 1);

			.coupon-list-main {
				transform: translateX(0);
			}
		}

		.coupon-box-close {
			position: absolute;
			right: 20rpx;
			top: 20rpx;
			font-size: 30rpx;
		}

		.coupon-box-title {
			text-align: center;
			line-height: 70rpx;
			margin-bottom: 20rpx;
			font-size: 30rpx;
			font-weight: bold;
		}

		.coupon-list {

			background: linear-gradient(90deg, #FBE2D0 0%, #FF8D1E 100%);
			border-radius: 10rpx;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
			height: 150rpx;
			padding: 0 20rpx;

			.coupon-list:last-child {
				margin-bottom: 0;
			}

			.coupon-symbol {
				font-size: 32rpx;
				color: #E26B3A;
			}

			.coupon-number {
				font-size: 56rpx;
				font-weight: bold;
				color: #E26B3A;
			}

			.coupon-title {
				color: #333;
				font-size: 32rpx;
			}

			.coupon-tips {
				color: #666;
				font-size: 28rpx;
				margin-top: 10rpx;
			}

			.coupon-btn {
				color: #fff;
				background-color: #E95249;
				width: 140rpx;
				height: 60rpx;
				font-size: 28rpx;
				border-radius: 60rpx;
			}

			.unavaliable-btn {
				background-color: #999;
			}

			.dec-parent {
				position: relative;
				border-left: dashed 1px #eee;
				height: 100%;
				width: 1px;
				margin-right: 20rpx;
			}

			.coupon-dec {
				width: 20rpx;
				height: 20rpx;
				border-radius: 20rpx;
				background-color: #fff;
				position: absolute;
			}

			.dec-top {
				top: -10rpx;
				left: -10rpx
			}

			.dec-bottom {
				bottom: -10rpx;
				left: -10rpx
			}
		}
	}
</style>